package person

import entity.Address
import entity.Person
import grails.converters.JSON
import grails.converters.XML
import org.codehaus.groovy.grails.web.json.JSONObject

class PersonController {
    static layout = "main"

    def index() {}

    def createPerson() {}
/*
create and save person to bd
 */

    def createPersonAction() {
        GregorianCalendar date = new GregorianCalendar
                (params.date_year as int, (params.date_month as int) - 1, params.date_day as int)


        def person = new Person(params)
        person.date = date.getTime()
        def address = new Address(params)
        person.address = address//set.address

        if (person.validate()) {
            person.save()
        }

        render template: "table",
                model: [persons: Person.findAll("from Person", [offset: (params.offset?:0) as int, max:5]),
                        personCount: Person.count()]
    }



    def deletePerson() {
        Person person = Person.get(params.id as long);// получаем person по id
        person.delete(flush: true)
        redirect action: "show"
    }

    def updatePersonAJAX() {
        String personInString = params.person
        JSONObject personInJSONObject = JSON.parse(personInString)

        Person personUpdate = Person.get(personInJSONObject.get('id') as long)
        println(" myPerson",personUpdate)
        personUpdate.name = personInJSONObject.get('name') as String
        personUpdate.age = personInJSONObject.get('age') as int
        personUpdate.address.city = personInJSONObject.get('city') as String
        personUpdate.address.street = personInJSONObject.get('street') as String
        personUpdate.address.number = personInJSONObject.get('number') as String

        personUpdate.save()

        render template: "table",
                model: [persons    : Person.findAll("from Person", [offset: (params.offset ?: 0) as int, max: 5]),
                        personCount: Person.count()]

    }

    def show() {
        List<Person> persons = Person.findAll("from Person", [offset: (params.offset ?: 0) as int, max: 5])
        println(persons)
        println(Person.count())
        println(params.offset)
        [persons: persons, personCount: Person.count(), offset: (params.offset ?: 0)]
//send map with personList to pages.gsp

    }

}
